package com.superpai.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.superpai.R;
import com.superpai.api.ItemAPI;
import com.superpai.domain.DBProduct;
import com.superpai.response.item.GetItemResponse;
import com.superpai.utils.AndroidUtils;
import com.superpai.utils.StringUtils;
import com.superpai.view.adapter.ProductDetailAdapter;
import com.superpai.view.custom.MirrorGallery;
import com.superpai.view.custom.ProductImageDialog;
import com.superpai.view.db.CartDBHelper;
import com.superpai.view.db.MyStoreDBHelper;

/**
 * @author Devin.Hu
 * @date 2011-9-9
 * @version V1.0
 * @description 产品详情页面
 */
public class ProductDetailActivity extends BaseActivity implements OnCheckedChangeListener , OnItemClickListener , OnCancelListener {

	private String itemCode;
	private int buycount;
	private final int GETPRODUCT = 1;
	private RadioGroup product_operate_group;
	private GetItemResponse response;
	private ProductDetailAdapter adapter;
	private MirrorGallery product_info_gallery;
	private ProductImageDialog mImageDialog;
	
	private TextView product_name;
	private TextView product_price;
	private TextView product_storecount;
  	private TextView procut_cityId;
  	private TextView procut_addtime;
  	private TextView procut_guaranteeRepair;
  	private TextView procut_recommendItem;
  	private TextView procut_secondHandItem;
  	private TextView procut_invoiceItem;
  	private TextView procut_sellerPayFreight;
  	private TextView procut_expressPrice;
  	private TextView procut_emsPrice;
  	private TextView procut_mailPrice;
  	private TextView procut_guarantee14Days;
  	private TextView procut_guarantee7Daysn;
  	private TextView procut_guaranteeCompensation;
  	
	private WebView product_detail_str;
	private List<String> mList;
	private LinearLayout product_tab_layout;
	
	//private TextView product_nowbuy_button;
	private Button product_buy_button;
	private Button product_store_button;
	private Button product_share_button;
	
	private TextView product_plusnum;
	private TextView product_addnum;
	private TextView product_num;
	
	
	@Override
	public void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		this.setContentView(R.layout.products_detail);
		initMenuView(this, mIndexBrand);
		initViews();
	}
	
	public void initViews(){
		
		mContext = this;
		Intent intent = this.getIntent();
		itemCode = intent.getStringExtra("itemCode") == null ? "" : intent.getStringExtra("itemCode");
		
		title = (TextView)this.findViewById(R.id.title);
		title.setText(R.string.product_detail_info_str);
		
		mProgress = (ProgressBar)this.findViewById(R.id.progress);
		mRefresh = (Button)this.findViewById(R.id.refresh);
		mRefresh.setOnClickListener(this);
		mNodata = (TextView)this.findViewById(R.id.nodata);
		
		product_num = (TextView)this.findViewById(R.id.product_num);
		product_plusnum = (TextView)this.findViewById(R.id.product_plusnum);
		product_plusnum.setOnClickListener(this);
		product_addnum = (TextView)this.findViewById(R.id.product_addnum);
		product_addnum.setOnClickListener(this);
		
		product_name = (TextView)this.findViewById(R.id.product_name);
		product_price = (TextView)this.findViewById(R.id.product_price);
		product_storecount = (TextView)this.findViewById(R.id.product_storecount);
		
	  	procut_cityId = (TextView)this.findViewById(R.id.procut_cityId);
	  	procut_addtime = (TextView)this.findViewById(R.id.procut_addtime);
	  	procut_guaranteeRepair = (TextView)this.findViewById(R.id.procut_guaranteeRepair);
	  	procut_recommendItem = (TextView)this.findViewById(R.id.procut_recommendItem);
	  	procut_secondHandItem = (TextView)this.findViewById(R.id.procut_secondHandItem);
	  	procut_invoiceItem = (TextView)this.findViewById(R.id.procut_invoiceItem);
	  	procut_sellerPayFreight = (TextView)this.findViewById(R.id.procut_sellerPayFreight);
	  	procut_expressPrice = (TextView)this.findViewById(R.id.procut_expressPrice);
	  	procut_emsPrice = (TextView)this.findViewById(R.id.procut_emsPrice);
	  	procut_mailPrice = (TextView)this.findViewById(R.id.procut_mailPrice);
	  	procut_guarantee14Days = (TextView)this.findViewById(R.id.procut_guarantee14Days);
	  	procut_guarantee7Daysn = (TextView)this.findViewById(R.id.procut_guarantee7Daysn);
	  	procut_guaranteeCompensation = (TextView)this.findViewById(R.id.procut_guaranteeCompensation);
	  	
		product_detail_str = (WebView)this.findViewById(R.id.product_detail_str);
		WebSettings webSettings = product_detail_str.getSettings();   
		webSettings.setBuiltInZoomControls(true);
		webSettings.setSupportZoom(true);
		product_detail_str.setInitialScale(Integer.parseInt(mContext.getString(R.string.product_detail_scale)));
		
		product_tab_layout = (LinearLayout)this.findViewById(R.id.product_tab_layout);
		product_tab_layout.getChildAt(0).setVisibility(View.VISIBLE);
		product_tab_layout.getChildAt(1).setVisibility(View.GONE);
		
		product_operate_group = (RadioGroup)this.findViewById(R.id.product_operate_group);
		product_operate_group.setOnCheckedChangeListener(this);
		
		product_info_gallery = (MirrorGallery)this.findViewById(R.id.product_info_gallery);
		adapter = new ProductDetailAdapter(mContext);
		product_info_gallery.setAdapter(adapter);
		product_info_gallery.setOnItemClickListener(this);
		
		//product_nowbuy_button = (TextView)this.findViewById(R.id.product_nowbuy_button);
		//product_nowbuy_button.setOnClickListener(this);
		product_buy_button = (Button)this.findViewById(R.id.product_buy_button);
		product_buy_button.setOnClickListener(this);
		product_store_button = (Button)this.findViewById(R.id.product_store_button);
		product_store_button.setOnClickListener(this);
		product_share_button = (Button)this.findViewById(R.id.product_share_button);
		product_share_button.setOnClickListener(this);
		
		connectionDate();
	}
	
	/**
	 * 读取商品信息
	 */
	private void connectionDate(){
		mRefresh.setVisibility(View.GONE);
		mNodata.setVisibility(View.GONE);
		mProgress.setVisibility(View.VISIBLE);
		onConnection(GETPRODUCT);
	}
	
	@Override
	public void onClick(View v) {
		
		checkMenu(v);
		
		if(v == product_plusnum){
			if(null != response){
				buycount--;
				if(buycount <= 0){
					buycount = 1;
				}
				product_num.setText(String.valueOf(buycount));
			}
		}
		
		if(v == product_addnum){
			if(null != response){
				buycount++;
				if(buycount >= Integer.parseInt(response.getStockCount())){
					buycount = Integer.parseInt(response.getStockCount());
				}
				product_num.setText(String.valueOf(buycount));
			}
		}

		//if(v == product_nowbuy_button){
			
		//}

		if(v == product_buy_button){
			buycount = Integer.parseInt(product_num.getText().toString());
			if(null != response && null != response.getItemCode()){
				CartDBHelper db  = new CartDBHelper(mContext);
				DBProduct cart = new DBProduct();
				cart.setPcode(response.getItemCode());
				cart.setPname(response.getItemName());
				cart.setPrice(response.getItemPrice());
				cart.setMprice(response.getMarketPrice());
				cart.setPimg(response.getPicLink());
				cart.setPnum(String.valueOf(buycount));
				boolean flag = db.saveItem(cart);
				if(flag){
					setProductCartNum(this);
					Builder builder = new AlertDialog.Builder(mContext);  
			        builder.setTitle(mContext.getString(R.string.common_tishi));  
			        builder.setMessage(mContext.getString(R.string.common_cart_suc));  
			        builder.setPositiveButton(mContext.getString(R.string.common_nowbuy),  
			                new DialogInterface.OnClickListener() {  
			                    public void onClick(DialogInterface dialog, int whichButton) {  
			                    	Intent intent = new Intent();
			                        intent.setClass(mContext, CartActivity.class);
			                        mContext.startActivity(intent);
			                    }  
			                });  
			        builder.setNegativeButton(mContext.getString(R.string.common_continue),  
			                new DialogInterface.OnClickListener() {  
			                    public void onClick(DialogInterface dialog, int whichButton) {  
			                        Intent intent = new Intent();
			                        intent.setClass(mContext, CategoryActivity.class);
			                        mContext.startActivity(intent);
			                    }  
			                });  
			        builder.show();  
				}else{
					AndroidUtils.Toast(mContext, mContext.getString(R.string.common_cart_exits));
				}
			}
		}
		if(v == product_store_button){
			if(null != response && null != response.getItemCode()){
				MyStoreDBHelper db  = new MyStoreDBHelper(mContext);
				DBProduct store = new DBProduct();
				store.setPcode(response.getItemCode());
				store.setPname(response.getItemName());
				store.setPrice(response.getItemPrice());
				store.setPimg(response.getPicLink());
				boolean flag = db.saveItem(store);
				if(flag){
					AndroidUtils.Toast(mContext, mContext.getString(R.string.common_suc));
				}else{
					AndroidUtils.Toast(mContext, mContext.getString(R.string.common_exits));
				}
			}
		}
		if(v == product_share_button){
			if(null != response && null != response.getItemName() && !response.getItemName().equals("")){
				AndroidUtils.sharePaiPai("分享#"+response.getItemName()+"#来自Android客户端-拍拍客.",this);
			}
		}
	}

	@Override
	public Object doDataConnection(int type) {
		try {
			ItemAPI api = new ItemAPI();
			response = api.getItem(itemCode);
			if(response.isSuccess()){
				return STATUS_SUC;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return STATUS_ERR;
		}
		return STATUS_ERR;
	}

	@Override
	public void doProcessData(int type, Object... values) {
		int status = Integer.parseInt(values[0].toString());
		mProgress.setVisibility(View.GONE);
		if(status == STATUS_SUC){
			getImgList(response);
			adapter.setImgList(mList);
			adapter.notifyDataSetChanged();
			fillDate();
		}else if(status == STATUS_ERR){
			
		}
	}
	
	/**
	 * 得到图片列表
	 * 
	 * @param response
	 */
	public void getImgList(GetItemResponse response)
	{
		mList = new ArrayList<String>();
		
		String picLink = response.getPicLink();
		if(null != picLink && !picLink.equals("")){
			mList.add(picLink);
		}
		
		String picLin1 = response.getPicLin1();
		if(null != picLin1 && !picLin1.equals("")){
			mList.add(picLin1);
		}
		
		String picLin2 = response.getPicLin2();
		if(null != picLin2 && !picLin2.equals("")){
			mList.add(picLin2);
		}
		
		String picLin3 = response.getPicLin3();
		if(null != picLin3 && !picLin3.equals("")){
			mList.add(picLin3);
		}
		
		String picLin4 = response.getPicLin4();
		if(null != picLin4 && !picLin4.equals("")){
			mList.add(picLin4);
		}
	}
	
	/**
	 * 填充数据
	 */
	public void fillDate(){
		product_name.setText(response.getItemName());
		product_price.setText(response.getItemPrice()+"元");
		product_detail_str.loadDataWithBaseURL("",response.getDetailInfo(), "text/html", "UTF-8","");
		product_storecount.setText(String.format(mContext.getString(R.string.product_stockCount), response.getStockCount()));
	  	procut_cityId.setText(response.getCityId());
	  	procut_addtime.setText(response.getCreateTime());
	  	procut_guaranteeRepair.setText(StringUtils.isOrNo2String(response.getGuaranteeRepair()));
	  	procut_recommendItem.setText(StringUtils.isOrNo2String(response.getRecommendItem()));
	  	procut_secondHandItem.setText(StringUtils.isOrNo2String(response.getSecondHandItem()));
	  	procut_invoiceItem.setText(StringUtils.isOrNo2String(response.getInvoiceItem()));
	  	
	  	String sellerpayfreight = response.getSellerPayFreight();
	  	if(null != sellerpayfreight)
	  	{
			if(sellerpayfreight.equals("1")){
				sellerpayfreight = "卖家承担运费"; 
			}
			else if(sellerpayfreight.equals("2")){ 
				sellerpayfreight = "买家承担运费";
			}
			else if(sellerpayfreight.equals("3")){ 
				sellerpayfreight = "同城交易，无需运费";
			}else{
				sellerpayfreight = "买家承担运费";
			}
		}
	  	procut_sellerPayFreight.setText(sellerpayfreight);
	  	procut_expressPrice.setText(StringUtils.getFormatPrice(response.getExpressPrice()));
	  	procut_emsPrice.setText(StringUtils.getFormatPrice(response.getEmsPrice()));
	  	procut_mailPrice.setText(StringUtils.getFormatPrice(response.getMailPrice()));
	  	procut_guarantee14Days.setText(StringUtils.isOrNo2String(response.getGuarantee14Days()));
	  	procut_guarantee7Daysn.setText(StringUtils.isOrNo2String(response.getGuarantee7Days()));
	  	procut_guaranteeCompensation.setText(StringUtils.isOrNo2String(response.getGuaranteeCompensation()));
	  	
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

		if(product_info_gallery.getSelectedItemPosition() == position && mImageDialog == null){
			ImageView imageView = (ImageView)adapter.getView(position, null, null);
			Drawable drawable= imageView.getDrawable();
			mImageDialog = new ProductImageDialog(this);
			mImageDialog.setShowDrawable(drawable);
			mImageDialog.setOnCancelListener(this);
			mImageDialog.show();
		}
	}
	
	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		RadioButton product_info = (RadioButton)this.findViewById(R.id.product_info);
		RadioButton product_detail_info = (RadioButton)this.findViewById(R.id.product_detail_info);
		
		switch(checkedId){
			case R.id.product_info:
				product_info.setBackgroundResource(R.drawable.product_info_pressed);
				product_detail_info.setBackgroundDrawable(null);
				product_tab_layout.getChildAt(0).setVisibility(View.VISIBLE);
				product_tab_layout.getChildAt(1).setVisibility(View.GONE);
			break;
		
			case R.id.product_detail_info:
				product_detail_info.setBackgroundResource(R.drawable.product_info_pressed);
				product_info.setBackgroundDrawable(null);
				product_tab_layout.getChildAt(0).setVisibility(View.GONE);
				product_tab_layout.getChildAt(1).setVisibility(View.VISIBLE);
			break;
		}
	}


	@Override
	public void onCancel(DialogInterface dialog) {
		mImageDialog.setOnCancelListener(null);
		mImageDialog = null;
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		disConnection();
	}
}
